﻿using Corina.Commands;
using Corina.Datamodel.Entities;
using Corina.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace Corina.Lantern.Hub.Viewmodels
{
    public class LoginViewmodel : ViewmodelBase
    {
        private WebClient Client;
        private WebClient SlideClient;
        private Image ImageViewer { get; set; }
        private DispatcherTimer timer;

        public LoginViewmodel() {

            SlideCollection.Add(1);
            SlideCollection.Add(2);
            SlideCollection.Add(3);

            Client = new WebClient();
            SlideClient = new WebClient();
            Client.DownloadStringCompleted += GetPasswordCompleted;
            CoreClient.LoginCompleted += LoginCompleted;
            timer = new DispatcherTimer();

            timer.Interval = TimeSpan.FromSeconds(3);
            timer.Tick += timer_Tick;

            SlideClient.OpenReadCompleted += SlideClientOpenReadCompleted;
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            timer.Stop();
            if (SlideIndex < SlideCollection.Count - 1)
            {
                SlideIndex++;
            }
            else
            {
                SlideIndex = 0;
            }
            
        }

        public void UILoaded(object sender, EventArgs e)
        {
            Page page = sender as Page;
            ImageViewer = (Image)page.FindName("imageViewer");

            GetImage(SlideIndex);
            timer.Start();
        }

        private void SlideClientOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                BitmapImage image = new BitmapImage();
                image.SetSource(e.Result);
                ImageViewer.Source = image;
            }
            timer.Start();
        }

        private void LoginCompleted(object sender, DataService.LoginCompletedEventArgs e)
        {
            IsBusy = false;
            if (e.Error == null)
            {
                if (e.Result.Result == Enumerations.ResultValue.Succeed)
                {
                    var account = (UserInfo)e.Result.Entities.FirstOrDefault();
                    var level = (UserLevelInfo)e.Result.Entities[1];

                    DataContext.CurrentAccount = account;
                    DataContext.CurrentUserLevel = level;

                    LoginSucceed.Invoke(this, new LoginResultArgs(true));

                }
                else
                {
                    MessageBox.Show(GetOperateResult(e.Result.Result));
                }
            }
            else
            {
                MessageBox.Show(e.Error.Message);
            }
        }

        private void GetPasswordCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string password = e.Result;
            CoreClient.LoginAsync(LoginAccount, password);
        }

        #region Properties
        private string _account = string.Empty;
        public string LoginAccount
        {
            get { return _account; }
            set
            {
                _account = value;
                RaisePropertyChanged(() => LoginAccount);
                RaisePropertyChanged(() => LoginCommand);
            }
        }

        private string _password = string.Empty;
        public string LoginPassword
        {
            get { return _password; }
            set
            {
                _password = value;
                RaisePropertyChanged(() => LoginPassword);
                RaisePropertyChanged(() => LoginCommand);
            }
        }

        private bool _rememberAccount = false;
        public bool RememberAccount
        {
            get { return _rememberAccount; }
            set {
                RememberAccount = value;
                RaisePropertyChanged(() => RememberAccount);
            }
        }
        #endregion

        #region Command
        public ICommand LoginCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return LoginAccount.Trim().Length > 3 && LoginPassword.Length > 5 && !IsBusy; },
                    ExecuteCallback = delegate
                    {
                        IsBusy = true;
                        Client.DownloadStringAsync(new Uri(WebServiceAddress + "md5.aspx?key=" + LoginPassword, UriKind.RelativeOrAbsolute));
                    }
                };
            }
        }

        public ICommand ExitCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        App.Current.MainWindow.Close();
                    }
                };
            }
        }

        public ICommand GotoRegisterCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate {
                        DataContext.ViewUrl = "/Register";
                    }
                };
            }
        }
        #endregion

        public event EventHandler<LoginResultArgs> LoginSucceed = delegate { };

        #region Slide Show
        private int _slideIndex = 0;
        public int SlideIndex
        {
            get { return _slideIndex; }
            set {
                _slideIndex = value;
                RaisePropertyChanged(() => SlideIndex);
                SelectedSlide = SlideCollection[SlideIndex];
                GetImage(SlideIndex);
            }
        }

        private List<int> _slideCollection = new List<int>();
        public List<int> SlideCollection
        {
            get { return _slideCollection; }
            set {
                _slideCollection = value;
                RaisePropertyChanged(() => SlideCollection);
            }
        }

        private int _selectedSlide = 1;
        public int SelectedSlide
        {
            get { return _selectedSlide; }
            set
            {
                _selectedSlide = value;
                RaisePropertyChanged(() => SelectedSlide);
                int _index = SlideCollection.IndexOf(SelectedSlide);
                if (_index != SlideIndex)
                {
                    SlideIndex = _index;
                }
            }
        }

        private void GetImage(int index)
        {
            string url = string.Format("http://static.byshuju.cn/Welcome/{0}.jpg", SlideCollection[SlideIndex]);
            Uri imageUri = new Uri(url);
            try
            {
                SlideClient.OpenReadAsync(imageUri);
            }
            catch { }
        }
        #endregion
    }
}
